package com.zhx.filter;

import com.zhx.bean.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @program: web-framework
 * @author: zhx
 * @create: 2021-03-20 20:31
 **/
public class LoginFilter implements Filter {
    FilterConfig config;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config=config;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpSession session = request.getSession(false);
        String contextPath = request.getContextPath();
        if (session!=null){
            User user = (User) session.getAttribute("user");
            if (user!=null){//说明这个用户已经登陆了，直接进入LoginSuccess.jsp中
                response.sendRedirect(contextPath+"/login-"+user.getUsername()+".html");
            }
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        this.config=null;
    }
}
